package com.course.dao;

import java.util.List;

import com.course.domain.Course;
import com.course.hibernate.HibernateSessionFactory;

public class CourseDao extends SupperDao
{

	@SuppressWarnings( "unchecked" )
	public List< Course > getCourseList( Integer id )
	{
		String hql = "from Course c where c.teacher.id = " + id;
		return this.findByHQL( hql );
	}

	public boolean setFinish( int courseId )
	{
		Course course = ( Course )this.get( Course.class, courseId );
		if ( !course.isChooseStatus() )
		{
			course.setFinish( true );
			if ( this.update( course ) )
				return true;
		}
		return false;
	}

	@SuppressWarnings( "unchecked" )
	public long countOfCourse( int teacherId )
	{
		String hql = "select count(*) from Course where teacher.id = " + teacherId;
		List<Long> list = this.findByHQL( hql );
		return list.get( 0 );
	}

	@SuppressWarnings( "unchecked" )
	public List< Course > getCourses( int start, int length, int teacherId )
	{
		String hql = "from Course where teacher.id = " + teacherId;
		return this.findPaging( hql, start, length, null );
	}

	public boolean deleteCourseById( Integer id )
	{
		String hql = "delete from StuCour sc where sc.id.course.id = " + id;
		Course course = null;
		try
		{
			session = HibernateSessionFactory.getSession(); // 获取Session对象
			session.beginTransaction(); // 开启事物
			session.createQuery( hql ) // 创建Query对象
					.executeUpdate(); // 更新
			course = ( Course )session.get( Course.class, id );
			session.delete( course );
			session.getTransaction().commit(); // 提交事物
			session.close();
		} catch ( Exception e )
		{
			e.printStackTrace(); // 打印异常信息
			session.getTransaction().rollback(); // 回滚事物
			session.close();
			return false;
		}
		return true;
	}

	public boolean setCourseNoChoose( Integer id )
	{
		Course course = ( Course )this.get( Course.class, id );
		course.setChooseStatus( false );
		return this.update( course );
	}

}
